﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Linq;

namespace SingleBlog.UI.Filters
{
    using Core.Services;
    using Microsoft.AspNetCore.Mvc;
    using Core.Data;

    /// <summary>
    /// 表示进行安装检测的特性。
    /// </summary>
    /// <seealso cref="IAuthorizationFilter" />
    public class InstallationCheckAttribute : IAuthorizationFilter
    {
        const string INSTALL_KEY = "SingleBlog";
        private readonly IMemoryCache _cache;
        private readonly SettingService _settingService;
        private readonly SingleBlogDbContext _context;
        public InstallationCheckAttribute(IMemoryCache cache,
            SettingService settingService,
            SingleBlogDbContext context
            )
        {
            _cache = cache;
            _settingService = settingService;
            _context = context;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if(context.Filters.Any(m=>m is NoInstallationCheckAttribute))
            {                
                return;
            }

            if (!context.HttpContext.Items.TryGetValue(INSTALL_KEY, out object value))
            {
                context.HttpContext.Items[INSTALL_KEY] = _context.DatabaseExist() && _settingService.GetSystemSetting()!=null;               
            }

            if (!context.HttpContext.Items[INSTALL_KEY].To<bool>())
            {
                context.Result = new RedirectResult("/Install");
                return;
            }
        }       
    }

    /// <summary>
    /// 表示不进行安装前的检测。
    /// </summary>
    /// <seealso cref="Attribute" />
    /// <seealso cref="IFilterMetadata" />
    [AttributeUsage(AttributeTargets.Class)]
    public class NoInstallationCheckAttribute:Attribute, IFilterMetadata
    {

    }
}
